package com.snape.utils;

//import com.sun.tools.corba.se.idl.StringGen;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.*;
//import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by liuqingcan_snape on 2017/3/28.
 */

public class LoginUtils {
    private static final String loginUrl = "http://19.offcn.com/foreusertest/dologin/type/10/?callback=jQuery18003350482142741218_1488801165901";
//    http://19.offcn.com/foreusertest/dologin/type/10/?callback=jQuery18008838100353708445_1493541576060
    /**
     * java web模拟登录
     * @param username
     * @param userpwd
     * @return
     * @throws Exception
     */
    public  static  Map<String,String> LoginHelp(String username,String userpwd) throws Exception {
        Map<String, String> result = new HashMap<String, String>();

       //创建一个HttpClient
       RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
       CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

       try {
           //post 信息
           //构造post数据
           List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
           valuePairs.add(new BasicNameValuePair("isecode","0"));
           valuePairs.add(new BasicNameValuePair("username", username));
           valuePairs.add(new BasicNameValuePair("password", userpwd));
           valuePairs.add(new BasicNameValuePair("secode", ""));
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);

           //创建一个post请求
           HttpPost post = new HttpPost(loginUrl);
//        post.setHeader("Cookie", " cap_id=\"YjA5MjE0YzYyNGQ2NDY5NWJhMmFhN2YyY2EwODIwZjQ=|1437610072|e7cc307c0d2fe2ee84fd3ceb7f83d298156e37e0\"; ");

           //注入post数据
           post.setEntity(entity);
           HttpResponse httpResponse =  httpClient.execute(post);


           //打印登录是否成功信息
           String temp = printResponse(httpResponse);
           result.put("status",temp);

           //得到post请求返回的cookie信息
           String c = setCookie(httpResponse);
           System.out.print("查看当前用户登录后的cookie: " + c);
           result.put("cookie",c);

           /**
            *构造一个get请求，用来测试登录cookie是否拿到
            */
//           HttpGet g = new HttpGet("http://19.offcn.com/course/video/cid/8958/ctype/2/id/147658/");
//           //将cookie注入到get请求头当中
//           g.setHeader("Cookie",c);
//           CloseableHttpResponse r = httpClient.execute(g);
//           String content = EntityUtils.toString(r.getEntity());
//           System.out.println(content);
//           r.close();


       } catch (IOException e) {
           e.printStackTrace();
           result.put("status","n");
       } finally {
           try {
               httpClient.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }


       return result;
   }

    public static String isLoginSuccess(String responseString)throws ParseException , IOException{
        String flag = "n";
        // 获取响应消息实体
        String jsonResp = responseString.substring(responseString.indexOf("(")+1,responseString.indexOf(")"));
        System.out.print("响应消息实体: " + jsonResp);
        try {
            JSONObject jsonRespJson = new JSONObject(jsonResp);
            flag = jsonRespJson.getString("status");
            System.out.print(flag);
        } catch (JSONException e) {
            e.printStackTrace();
            return flag;
        }
        return flag;
    }



//    /**
//     * 构造一个get请求，用来测试登录cookie是否拿到
//     * @param httpResponse
//     * @throws IOException
//     */
//    public static void doAfterLoginRequest(HttpResponse httpResponse) throws IOException{
//        //创建一个HttpClient
//        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
//        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
//
//
//    }

    /**
     * 打印 http中response消息体
     * @param httpResponse
     * @throws ParseException
     * @throws IOException
     */
    public static String printResponse(HttpResponse httpResponse) throws ParseException, IOException {
        String result = "n";
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        System.out.println("status:" + httpResponse.getStatusLine());
        System.out.println("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            System.out.println("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            System.out.println("response length:" + responseString.length());
            System.out.println("response content:"
                    + responseString.replace("\r\n", ""));
            //解析http 中的 response
            result = isLoginSuccess(responseString);
        }
        return result;
    }

    public static Map<String,String> cookieMap = new HashMap<String, String>(64);

    /**
     * 从响应信息中获取cookie
     * @param httpResponse
     * @return
     */
    public static String setCookie(HttpResponse httpResponse)
    {
        System.out.println("----setCookieStore");
        Header headers[] = httpResponse.getHeaders("Set-Cookie");
        if (headers == null || headers.length==0)
        {
            System.out.println("----there are no cookies");
            return null;
        }
        String cookie = "";
        for (int i = 0; i < headers.length; i++) {
            cookie += headers[i].getValue();
            if(i != headers.length-1)
            {
                cookie += ";";
            }
        }

        String cookies[] = cookie.split(";");
        for (String c : cookies)
        {
            c = c.trim();
            if(cookieMap.containsKey(c.split("=")[0]))
            {
                cookieMap.remove(c.split("=")[0]);
            }
            cookieMap.put(c.split("=")[0], c.split("=").length == 1 ? "":(c.split("=").length ==2?c.split("=")[1]:c.split("=",2)[1]));
        }
        System.out.println("----setCookieStore success");
        String cookiesTmp = "";
        for (String key :cookieMap.keySet())
        {
            cookiesTmp +=key+"="+cookieMap.get(key)+";";
        }

        return cookiesTmp.substring(0,cookiesTmp.length()-2);
    }


    public static String getLoginUrl() {
        return loginUrl;
    }
}
